package com.yeren.weixin.gzh.weixin.operation;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class JsExecute {
	private static Logger log=LoggerFactory.getLogger(JsExecute.class);
	public static String get_JS_Signature(String jsapi_ticket,String noncestr,long timestamp,String url){
		String str = "jsapi_ticket=" + jsapi_ticket +"&noncestr=" + noncestr +"&timestamp=" + timestamp +"&url=" + url;
		String signature="";
		 try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(str.getBytes("UTF-8"));
	            return signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
	            e.printStackTrace();
	        }
	        catch (UnsupportedEncodingException e)
	        {
	            e.printStackTrace();
	        }
		return null;
	}
	
	public static String get_jsapi_ticket(String appid,String appsecret){
		//1获取accessToken
		String accessToken = TokenExecute.getToken(appid, appsecret).getAccessToken();
		//2获取JSTicket
		String requestUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject = CommonExecute.httpsRequest(requestUrl, "GET", null);
		String ticket = null;
	        if (null != jsonObject) {
	            try {
	                ticket = jsonObject.getString("ticket");
	            } catch (JSONException e) {
	                // 获取token失败
	                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
	            }
	        }
	    return ticket;
	} 
	
	private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
	
	
	public static void main(String[] args) {
//		String ticket=A.get_jsapi_ticket("wxf9b54a0426aab166", "8481d5df777deb142eb3a18b2691f95b");
		String ticket="sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg";
//		String noncestr=UUID.randomUUID().toString();
		String noncestr="Wm3WZYTPz0wzccnW";
//		long timestamp = System.currentTimeMillis() / 1000;
		long timestamp =1414587457;
//		String url="http://mp.weixin.qq.com?params=value";
		String url="http://yeren108.duapp.com";
		
		String signature=get_JS_Signature(ticket, noncestr, timestamp, url);
		System.out.println("signature:"+signature);
		
	}
}
